package com.jkdroid.maya.util;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;

import java.util.Calendar;

/**
 * 与Android系统相关的工具类
 * @author guanzhihao
 * @date   2015年12月14日
 *
 */
public class AppUtils {

    /**
     * 检查手机是否存在该Activity
     * @param context
     * @param packageName 包名
     * @param className Activity类名
     * @return true:存在，false:不存在
     */
    public static boolean hasActivity(Context context, String packageName, String className) {
        Intent intent = new Intent();
        intent.setClassName(packageName, className);
        if (context.getPackageManager().resolveActivity(intent, 0) == null) {
            // 不存在这个activity
            return false;
        }
        return true;
    }

    /**
     * 使用浏览器打开web网页
     * @param context
     * @param url 网页地址
     * @return true:打开成功， false打开失败，一般是手机没有浏览器应用
     */
    public static boolean showWeb(Context context, String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        String packageName = "com.android.browser";
        String className = "com.android.browser.BrowserActivity";
        try {
            intent.setClassName(packageName, className);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 延迟重启
     * @param context
     * @param delayMs 延迟毫秒数
     */
    public static void reboot(Context context, int delayMs) {
        try {
            PackageManager packageManager = context.getPackageManager();
            Intent intent = packageManager.getLaunchIntentForPackage(context.getPackageName());
            PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent,PendingIntent.FLAG_CANCEL_CURRENT);
            AlarmManager alarm;
            alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            alarm.set(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + delayMs, contentIntent);
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

	/**
	 * 清除掉利用使用reboot方法延迟重启的消息
	 * @param context
	 */
	public static void clearRebootPending(Context context){
		PackageManager packageManager = context.getPackageManager();
		Intent intent = packageManager.getLaunchIntentForPackage(context.getPackageName());
		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent,
				PendingIntent.FLAG_CANCEL_CURRENT);
		AlarmManager alarm;
		alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		alarm.cancel(contentIntent);
	}
    
    private AppUtils(){}
}
